package com.spark.gaea.crypto;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class Decrypter {
	private static final String PRIVATE_KEY_STRING = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAuG2EeHx9Z4lGyLKuP0D+/SIgotE1dQGBPOE02mSkGHROKuYL1zEV74syolbkIqhQc78/nvZDh+Dumkd6pzq02QIDAQABAkAfiDH++6HhQtpEVDBwhidSljQoQka2g5RaGVMVB+H6gBWk9UJ601hWLRwwalwPx46wLQPsa1JVjlXd8+xbNBQFAiEA6SZVlZbinUsqOLDAQknmiqimI14uWqVxMjJS0ihv9g8CIQDKgMMx6f6pxiLqayrUVdRtiq0t2611ZWE9yB+OxEhOlwIhANwDBLhIzkhIaetdP9BOFHO8eird8Tgw7wTDYExZRG4ZAiEArY9SvTMai5RAVL5pRPgTS5ex+j3wG1A62eLt+UUN3B0CIFYeY9K865X7NOcAbxUdhW+FSkmzdPeRa2RTfK2fG682";

	public static String decrypter(final String cipherText) throws Exception {
		final PrivateKey privateKey = getPrivateKey();
		final Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(2, privateKey);
		if (cipherText == null || cipherText.length() == 0) {
			return cipherText;
		}
		final byte[] cipherBytes = Base64.decodeBase64(cipherText);
		final byte[] plainBytes = cipher.doFinal(cipherBytes);
		return new String(plainBytes);
	}

	private static PrivateKey getPrivateKey() throws Exception {
		final byte[] decodeKeyinfo = Base64.decodeBase64(
				"MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAuG2EeHx9Z4lGyLKuP0D+/SIgotE1dQGBPOE02mSkGHROKuYL1zEV74syolbkIqhQc78/nvZDh+Dumkd6pzq02QIDAQABAkAfiDH++6HhQtpEVDBwhidSljQoQka2g5RaGVMVB+H6gBWk9UJ601hWLRwwalwPx46wLQPsa1JVjlXd8+xbNBQFAiEA6SZVlZbinUsqOLDAQknmiqimI14uWqVxMjJS0ihv9g8CIQDKgMMx6f6pxiLqayrUVdRtiq0t2611ZWE9yB+OxEhOlwIhANwDBLhIzkhIaetdP9BOFHO8eird8Tgw7wTDYExZRG4ZAiEArY9SvTMai5RAVL5pRPgTS5ex+j3wG1A62eLt+UUN3B0CIFYeY9K865X7NOcAbxUdhW+FSkmzdPeRa2RTfK2fG682");
		final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodeKeyinfo);
		final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(keySpec);
	}
}
